import useRequest from "@/api/useRequest";

export class mjControllerApi {


  static async generateText2ImgAndCheck(data: any, timeoutMs: number ,progress:any, imageUrl:any): Promise<any> {
    try {
      // 发送任务提交请求
      const response = await useRequest({
        url: "/mj/submit",
        method: "post",
        data,
      });
      const taskId = response.data.result;
      let polling = true; // 添加一个轮询标志变量
      const pollTaskStatus: () => Promise<any> = async () => {
        console.log('pollTaskStatus{}检查状态')
        try {

          if (!polling) {
            // 如果轮询被标志为停止，则返回 null
            return null;
          }
          // 发送任务状态检查请求
          const statusResponse = await useRequest({
            url: "/mj/taskInfo/" + taskId,
            method: "get",
          });
          const status = statusResponse.data.status;
          if (status === "NOT_START" || status === "SUBMITTED" || status === "IN_PROGRESS") {
            if (status === "IN_PROGRESS") {
              progress.value = statusResponse.data.progress;
              imageUrl.value = statusResponse.data.imageUrl;
            }
            // 继续轮询
            await new Promise(resolve => setTimeout(resolve, 5000)); // 等待5秒
            return pollTaskStatus(); // 继续轮询
          } else {

            if (status === "SUCCESS") {
              console.log(statusResponse);
              // 返回任务制作成功的结果
              return statusResponse.data;
            } else {
              // 返回任务制作失败的结果
              throw new Error("任务制作失败");
            }
          }
        } catch (error) {
          throw new Error("任务状态检查失败");
        }
      };

      // 使用 Promise.race 来同时等待任务完成和超时时间的先发生
      const result = await Promise.race([
        pollTaskStatus(),
        new Promise((_, reject) => {
          setTimeout(() => {
            polling = false
            reject(new Error("任务超时"));
          }, timeoutMs);
        }),
      ]);
      console.log('result:{}', result)
      return result;
    } catch (error) {
      throw new Error("提交任务失败");
    }
  }

  /**
   * 根据prompt想象成图
   * @param data
   */
  static imagine(data: any): Promise<any> {
    return useRequest({
      url: "/mj/submit",
      method: "post",
      data
    })
  }





  static history(): Promise<any> {
    return useRequest({
      url: "/mj/task/history",
      method: "get"
    })
  }

  /**
   * 图片转换
   * @param data
   */
  static change(data: any): Promise<any> {
    return useRequest({
      url: "/gps/art/mj/change",
      method: "post",
      data
    })
  }


  static checkTask(taskId: string): Promise<any> {
    return useRequest({
      url: "/gps/mj/task/" + taskId + "/fetch",
      method: "get",
    })
  }

  /**
   * 获取绘图记录
   */
  static getPaintRecords(): Promise<any> {
    return useRequest({
      url: "/gps/mj/task/listHistory",
      method: "get",
    })
  }

  static getStatus(): Promise<any>{
    return useRequest({
      url: "/mj/status",
      method: "get",
    })
  }

  static reConnect(): Promise<any>{
    return useRequest({
      url: "/mj/reConnect",
      method: "get",
    })
  }

  static getMjUnfinishedTask(): Promise<any>{
    return useRequest({
      url: "/mj/task/unfinished",
      method: "get",
    })
  }

  static killMjTask(taskId: string): Promise<any>{
    return useRequest({
      url: "/mj/task/kill/" + taskId,
      method: "get",
    })
  }

}
